package com.company;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * Created by Kaige on 2018/2/24 0024.
 */
public class SimpleZkClient {

    private final static String SERVERS = "zk01:2181,zk02:2181,zk03:2181";
    private final static int SESSION_TIMEOUT = 2000;


    private ZooKeeper mZkClient;
    private CountDownLatch mDownLatch = new CountDownLatch(1);

    public SimpleZkClient() {
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Before
    public void init() throws Exception{
        mZkClient = new ZooKeeper(SERVERS, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if(watchedEvent.getState()== Watcher.Event.KeeperState.SyncConnected){
                    System.out.println("countdown");
                    mDownLatch.countDown();
                }

                System.out.println(watchedEvent.getType()+"----"+watchedEvent.getPath());
                System.out.println(watchedEvent.getState());
            }
        });
        mDownLatch.await();
    }

    @Test
    public void testCreate() throws KeeperException, InterruptedException {
        mZkClient.create("/test","hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        mZkClient.close();
    }
}
